<template>
  <div class="edit-container">
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-form-item label="菜品名称：" prop="name">
        <el-input v-model="ruleForm.name" placeholder="请选择菜品名称" />
      </el-form-item>
      <el-form-item label="菜品分类：" prop="categoryId">
        <el-select v-model="ruleForm.categoryId" placeholder="请选择菜品分类">
          <el-option
            v-for="item in cateNameList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="菜品价格：" prop="price">
        <el-input
          v-model.number="ruleForm.price"
          placeholder="请选择菜品价格"
        />
      </el-form-item>
      <el-form-item label="口味做法配置：">
        <el-button
          v-if="!isShow"
          class="addBtn"
          @click="
            isShow = !isShow
            addFlavor()
          "
        >
          + 添加口味
        </el-button>
        <div v-else class="configDiv">
          <div class="tips">口味名（3个字内）口味标签（输入标签回车添加）</div>
          <div
            v-for="(item, index1) in ruleForm.flavors"
            :key="index1"
            class="configRow"
          >
            <el-autocomplete
              v-model="item.name"
              class="inline-input"
              :fetch-suggestions="querySearch"
              placeholder="请输入口味名"
              @select="handleSelect"
            />
            <div class="tags">
              <el-tag
                v-for="(tag, index2) in item.value"
                :key="index2"
                closable
                :disable-transitions="false"
                @close="handleClose(index1, index2)"
              >
                {{ tag }}
              </el-tag>
            </div>
            <el-input
              v-model="item.iptVal"
              class="autoWidth"
              placeholder="请输入口味标签"
              @keyup.enter.native="handleInputConfirm(index1)"
            />
            <el-button
              type="text"
              size="medium"
              class="textColor"
              @click="delFlavor"
              >删除</el-button
            >
          </div>
          <div class="addRow">
            <el-button class="orangeElButton" @click="addFlavor"
              >添加口味</el-button
            >
          </div>
        </div>
      </el-form-item>
      <el-form-item label="菜品图片：" prop="image">
        <el-upload
          class="upload-demo"
          action="/dev-api/common/upload"
          :on-success="handleSuccess"
          :on-exceed="handleExceed"
          list-type="picture-card"
          :file-list="fileList"
          :limit="1"
        >
          <i slot="default" class="el-icon-plus" />
          <div slot="file" slot-scope="{ file }">
            <img
              class="el-upload-list__item-thumbnail"
              :src="file.url"
              alt=""
            />
            <span class="el-upload-list__item-actions">
              <span
                class="el-upload-list__item-preview"
                @click="handlePreview(file)"
              >
                <i class="el-icon-zoom-in" />
              </span>
              <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
              >
                <i class="el-icon-delete" />
              </span>
            </span>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="菜品描述：" prop="description">
        <el-input
          v-model="ruleForm.description"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4 }"
          placeholder="菜品描述，最长200字"
        />
      </el-form-item>
      <el-form-item class="btn">
        <el-button class="cancelBtn" @click="$router.go(-1)">取消</el-button>
        <el-button class="saveBtn" @click="submitForm('ruleForm')"
          >保存</el-button
        >
        <el-button
          class="saveAddBtn"
          @click="submitForm('ruleForm')"
          v-if="myType === 'add'"
          >保存并添加</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 点击预览的弹出框 -->
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import { getCategoryByType } from '@/api/category'
import { addDish, getDishById, editDish } from '@/api/dish'
export default {
  name: 'EditDish',

  beforeRouteEnter (to, from, next) {
    const type = to.params.myType
    if (type === 'add') {
      to.meta.title = '新增菜品'
    } else if (type === 'edit') {
      to.meta.title = '修改菜品'
    }
    next()
  },

  props: {
    myType: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      default: ''
    }
  },

  data () {
    return {
      ruleForm: {
        name: '',
        categoryId: '',
        price: '',
        // 收集口味的数组
        flavors: [],
        // 图片
        image: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '请输入菜品名称', trigger: 'blur' }],
        categoryId: [
          { required: true, message: '请选择菜品分类', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入菜品价格', trigger: 'blur' },
          { type: 'number', message: '菜品价格必须为数字值' }
        ],
        image: [{ required: true, message: '请上传图片', trigger: 'change' }]
      },

      fileList: [],

      // 控制 configDiv 的显示与隐藏
      isShow: false,

      // 新增或编辑前调用接口获取菜品下的分类
      cateList: [],

      // 预览图
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,

      // 输入建议
      suggestList: []
    }
  },

  computed: {
    cateNameList () {
      return this.cateList.map(item => {
        return { name: item.name, id: item.id }
      })
    }
  },

  watch: {
    'ruleForm.flavors': {
      handler (obj) {
        if (!obj.length) {
          this.isShow = false
        } else {
          this.isShow = true
        }
      },
      immediate: true,
      deep: true
    },

    $route: {
      async handler () {
        const res = await getCategoryByType({ type: 1 })
        this.cateList = res.data
      },
      immediate: true
    }
  },

  async created () {
    if (this.myType === 'edit') {
      // console.log(this.id)
      const { data } = await getDishById(this.id)
      // console.log(data)
      for (const key in data) {
        if (data['hasOwnProperty'](key)) {
          if (key === 'price') {
            this.ruleForm['price'] = data.price / 100
          } else if (key === 'image') {
            this.fileList.push({
              url:
                process.env.VUE_APP_BASE_API +
                '/common/download?name=' +
                data.image
            })

            this.ruleForm.image = data.image
          } else if (key === 'flavors') {
            data.flavors.forEach(item => {
              item.iptVal = ''
              item.value = JSON.parse(item.value)
            })
            this.$set(this.ruleForm, 'flavors', data.flavors)
          } else {
            this.ruleForm[key] = data[key]
          }
        }
      }
    }
  },

  mounted () {
    this.suggestList = this.loadAll()
  },

  methods: {
    /* 选取图片相关的处理函数 */
    handleRemove () {
      this.fileList.pop()
    },
    handlePreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleSuccess (res, file) {
      // console.log(res)
      this.fileList.push(file)
      if (res.code === 1) {
        this.ruleForm.image = res.data
      }
    },
    handleExceed () {
      Message({
        message: '只能选择一张图片',
        type: 'error',
        duration: 3 * 1000
      })
    },

    // 确认后生成 tag
    handleInputConfirm (index1) {
      // 对应的 configRow
      const item = this.ruleForm.flavors[index1]
      // 标签输入框对应值
      const iptVal = item.iptVal
      if (iptVal.trim()) {
        item.value.push(iptVal)
        item.iptVal = ''
      }
    },

    // 关闭某个 tag
    handleClose (index1, index2) {
      // 对应的 configRow
      const item = this.ruleForm.flavors[index1]
      // 对应的标签数组
      const value = item.value
      value.splice(index2, 1)
      if (!value.length) {
        this.ruleForm.flavors.splice(index1, 1)
      }
    },

    // 添加口味
    addFlavor () {
      this.ruleForm.flavors.push({ name: '', value: [], iptVal: '' })
    },
    // 删除口味
    delFlavor () {
      if (this.ruleForm.flavors.length) {
        this.ruleForm.flavors.pop()
      }
    },
    // 保存
    submitForm (formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          const ruleForm = this.ruleForm
          let finalForm = Object.assign({}, ruleForm, {
            price: ruleForm.price * 100,
            flavors: ruleForm.flavors.map(item => {
              return {
                name: item.name,
                showOption: false,
                value: JSON.stringify(item.value)
              }
            })
          })
          if (this.myType === 'add') {
            finalForm = Object.assign(finalForm, { status: 1, code: '' })
            const res = await addDish(finalForm)
            if (res.code === 1) {
              // console.log(res.data)
              this.$message({
                message: '新增菜品成功！',
                type: 'success',
                duration: 3 * 1000
              })
              // 清空表单
              this.$refs[formName].resetFields()
              // 跳转到 /dish/index
              this.$router.push({ path: '/cuisine/index' })
            }
          } else if (this.myType === 'edit') {
            const res = await editDish(finalForm)
            if (res.code === 1) {
              this.$message({
                message: '修改菜品成功！',
                type: 'success',
                duration: 3 * 1000
              })
              // 清空表单
              this.$refs[formName].resetFields()
              this.$router.push({ path: '/cuisine/index' })
            }
          }
          // console.log(finalForm)
        } else {
          alert('no')
          return false
        }
      })
    },

    /* 输入建议 */
    loadAll () {
      return [
        {
          value: '甜度',
          values: ['无糖', '少糖', '半糖', '多糖', '全糖']
        },
        {
          value: '温度',
          values: ['热饮', '常温', '去冰', '少冰', '多冰']
        },
        {
          value: '忌口',
          values: ['不要葱', '不要蒜', '不要香菜', '不要辣']
        },
        {
          value: '辣度',
          values: ['不辣', '微辣', '中辣', '重辣']
        }
      ]
    },
    querySearch (queryString, cb) {
      const suggestList = this.suggestList
      const results = queryString
        ? suggestList.filter(this.createFilter(queryString))
        : suggestList
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter (queryString) {
      return sugg => {
        return sugg.value.indexOf(queryString) === 0
      }
    },
    handleSelect (item) {
      // console.log(item)
      this.ruleForm.flavors.find(flavor => flavor.name === item.value).value =
        item.values
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';
@import '@/styles/mixin.scss';

.edit-container {
  padding: 20px;

  .el-form {
    background-color: $whitecolor;
    padding: 20px;
    border-radius: 4px;

    .el-tag {
      margin-left: 10px;
    }

    .el-input,
    .el-select {
      width: 250px;
    }

    .configDiv {
      border: 1px solid #dfe2e8;
      border-radius: 3px;
      background-color: #fafafb;
      padding: 15px;

      .configRow {
        margin: 10px 0;
        display: flex;

        .el-input:first-of-type {
          flex-basis: 150px;
        }
        .autoWidth {
          flex: auto;
          margin: 0 10px;
        }
      }
    }
  }
  .btn {
    display: flex;
    justify-content: center;
    ::v-deep .el-form-item__content {
      margin-left: 0 !important;
    }
  }
  .addBtn {
    background-color: $darkorange;
    color: $darkblack;
  }

  .saveBtn {
    background-color: $darkorange;
    color: $darkblack;
    &:hover {
      background-color: $lightorange;
    }
  }
  .saveAddBtn {
    background-color: $darkblack;
    color: #fff;
    &:hover {
      background-color: $lightblack;
    }
  }

  .textColor {
    color: #f56c6c;
  }
}
</style>
